from drf_haystack.serializers import HaystackSerializer
from rest_framework import serializers

from course.models import CategoryModel, CourseModel
from course.search_indexes import CourseIndex


class Category(serializers.ModelSerializer):
    class Meta:
        model = CategoryModel
        fields = ['c_name', 'id']


class CategorySerializer(serializers.ModelSerializer):
    children = Category(many=True)

    class Meta:
        model = CategoryModel
        fields = '__all__'


class CourseSerializer(serializers.ModelSerializer):
    tea = serializers.SerializerMethodField(read_only=True)

    def get_tea(self, obj):
        return {
            't_name': obj.teacher.t_name,
            'job': obj.teacher.job,
            'head_img': "http://127.0.0.1:8000/uploads" + str(obj.teacher.head_img),
            'intro': obj.teacher.intro
        }

    class Meta:
        model = CourseModel
        fields = '__all__'


# 索引的序列化器
class CourseIndexSerializer(HaystackSerializer):
    class Meta:
        index_classes = [CourseIndex]
        fields = ["text", 'id', 'c_name', 'content', 'teacher', 'cover', 'price', 'discount']
